import CryptoJs from 'crypto-js';
import { _localUserInfo } from '../util/authUserInfo/userInfo';
import { getaccessTokenOnlyByTokenSNO } from '../api/getAuth';
import { getAesKey } from '../api/getAesKey';

/**
 *
 * @param {'解密值'} word   
 * @returns
 */
function newDecrypt(word: string): Promise<string> {
    return new Promise(async (resove, reject) => {
        let tokenSNO = _localUserInfo();
        // console.log(tokenSNO);
        let accessToken = await getaccessTokenOnlyByTokenSNO({
            tokenSNO: tokenSNO.token as string,
        });
        let key = await getAesKey({ accessToken: accessToken.access_token });
        let keyIv = CryptoJs.enc.Utf8.parse(key.newDefaultKey);
        var decrypt = CryptoJs.AES.decrypt(word, keyIv, {
            mode: CryptoJs.mode.ECB,
            padding: CryptoJs.pad.Pkcs7,
        });
        resove(CryptoJs.enc.Utf8.stringify(decrypt).toString());
    });
}

/**
 *
 * @param {'加密值（序列化）'} word
 * @returns
 */
function newEncrypt(word: string): Promise<string> {
    return new Promise(async (resove, reject) => {
        let tokenSNO = _localUserInfo();
        // console.log(tokenSNO);
        let accessToken: any = await getaccessTokenOnlyByTokenSNO({
            tokenSNO: tokenSNO.token as string,
        });
        let key = await getAesKey({ accessToken: accessToken.access_token });
        let keyIv = CryptoJs.enc.Utf8.parse(key.newDefaultKey);
        var srcs = CryptoJs.enc.Utf8.parse(word);
        var encrypted = CryptoJs.AES.encrypt(srcs, keyIv, {
            mode: CryptoJs.mode.ECB,
            padding: CryptoJs.pad.Pkcs7,
        }); // 加密模式为ECB，补码方式为PKCS5Padding（也就是PKCS7）
        resove(encrypted.toString());
    });
}

export { newDecrypt, newEncrypt }